#!/usr/bin/env python
# -*- coding: utf8 -*-
from google.appengine.api import urlfetch
#import json
from django.utils import simplejson as json
import urllib

class GoogleAPIException(Exception):
    pass

class GoogleAPI:
    def __init__(self, language = 'en', key = None):
        self.methods = ['web', 'local', 'video', 'blogs', 'news', 'books', 'images', 'patent']
        self.host = 'ajax.googleapis.com'
        self.url = '/ajax/services/search/'
        self.params = {'q': '',
                       'v': '1.0',
                       'rsz': 'large',
                       'hl': language,
                       'key': key
                       }
    
    def _doSearch(self, query):
        url = 'http://' + self.host + self.url + query
        resp = urlfetch.fetch(url)
        if resp.status_code == 200:
            data = resp.content
            return data
        else:
            raise GoogleAPIException
            return

    def _jsonParser(self, data):
        return json.loads(data)

    def _search(self, method, question):
        params = self.params.copy()
        params['q'] = question.encode('utf8')
        query = method + '?' + urllib.urlencode(params)
        data = self._doSearch(query)
        return self._jsonParser(data)

    def searchWeb(self, question):
        return self._search('web', question)['responseData']['results']

def test():
    gapi = GoogleAPI('zh-CN', settings.googleapikey)
    data = gapi.searchWeb(u'中国')
    print data

if __name__ == '__main__':
    test()